<template>
  <view class="history-container">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="nav-left">
        <text class="back-icon" @tap="goBack">←</text>
      </view>
      <view class="nav-center">
        <text class="nav-title">播放历史</text>
      </view>
      <view class="nav-right">
        <text class="clear-icon" @tap="clearHistory">清空</text>
      </view>
    </view>

    <!-- 页面标题区域 -->
    <view class="page-header">
      <text class="page-title">播放历史</text>
      <text class="page-subtitle">共 {{ historyList.length }} 首歌曲</text>
    </view>

    <!-- 历史列表 -->
    <view class="history-list">
      <view v-if="historyList.length === 0" class="empty-state">
        <text class="empty-icon">🎵</text>
        <text class="empty-text">暂无播放历史</text>
        <text class="empty-desc">去听听好听的音乐吧</text>
        <button class="empty-btn" @tap="goToHome">去发现</button>
      </view>

      <view v-else class="song-list">
        <view 
          v-for="(history, index) in historyList" 
          :key="history.id" 
          class="song-item"
        >
          <view class="song-info" @tap="playSong(history)">
            <image :src="history.coverUrl" class="song-cover" mode="aspectFill" />
            <view class="song-details">
              <text class="song-name">{{ history.songTitle }}</text>
              <text class="song-artist">{{ history.artist }}</text>
              <text class="song-time">播放于 {{ formatTime(history.playTime) }}</text>
            </view>
          </view>
          
          <view class="song-actions">
            <text class="play-btn" @tap.stop="playSong(history)">▶</text>
            <text class="remove-btn" @tap.stop="removeFromHistory(history)">×</text>
          </view>
        </view>
      </view>
    </view>

  </view>
</template>

<script>
import userManager from '@/utils/user.js'
import historyManager from '@/utils/history.js'

export default {
  data() {
    return {
      historyList: [],
      isLogin: false
    }
  },
  
  onLoad() {
    this.checkLoginStatus()
  },
  
  onShow() {
    this.checkLoginStatus()
    if (this.isLogin) {
      this.getHistory()
    }
  },
  
  methods: {
    // 检查登录状态
    checkLoginStatus() {
      this.isLogin = userManager.checkLogin()
      if (!this.isLogin) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      }
    },
    
    // 获取播放历史
    async getHistory() {
      if (!this.isLogin) {
        this.historyList = []
        return
      }
      
      try {
        const userId = userManager.getUserId()
        this.historyList = historyManager.getUserHistory(userId)
      } catch (error) {
        console.error('获取播放历史失败:', error)
        this.historyList = []
      }
    },
    
    // 播放歌曲
    playSong(history) {
      // 获取全局音乐播放器实例
      const pages = getCurrentPages()
      const currentPage = pages[pages.length - 1]
      
      // 如果是从首页跳转过来的，尝试调用首页的播放器
      if (currentPage.route === 'pages/home/home') {
        const homePage = getCurrentPages().find(page => page.route === 'pages/home/home')
        if (homePage && homePage.$vm && homePage.$vm.$refs.musicPlayer) {
          const songInfo = {
            id: history.songId,
            name: history.songTitle,
            artist: history.artist,
            cover: history.coverUrl,
            url: this.getSongUrl(history.songId)
          }
          homePage.$vm.$refs.musicPlayer.playSong(songInfo)
        }
      }
      
      uni.showToast({
        title: `播放 ${history.songTitle}`,
        icon: 'none'
      })
    },
    
    // 获取歌曲URL（模拟）
    getSongUrl(songId) {
      // 这里可以根据songId返回对应的歌曲URL
      const songUrls = {
        1: 'https://music.163.com/song/media/outer/url?id=519909355.mp3',
        2: 'https://music.163.com/song/media/outer/url?id=139774.mp3',
        3: 'https://music.163.com/song/media/outer/url?id=409916250.mp3',
        4: 'https://music.163.com/song/media/outer/url?id=516076896.mp3'
      }
      return songUrls[songId] || 'https://music.163.com/song/media/outer/url?id=519909355.mp3'
    },
    
    // 从历史记录中移除
    async removeFromHistory(history) {
      uni.showModal({
        title: '确认移除',
        content: `确定要从播放历史中移除「${history.songTitle}」吗？`,
        success: async (res) => {
          if (res.confirm) {
            try {
              const userId = userManager.getUserId()
              await historyManager.removeFromHistory(userId, history.songId)
              this.getHistory() // 重新获取列表
              uni.showToast({
                title: '已移除',
                icon: 'success'
              })
            } catch (error) {
              uni.showToast({
                title: '移除失败',
                icon: 'none'
              })
            }
          }
        }
      })
    },
    
    // 清空播放历史
    clearHistory() {
      if (this.historyList.length === 0) {
        uni.showToast({
          title: '历史记录已为空',
          icon: 'none'
        })
        return
      }
      
      uni.showModal({
        title: '确认清空',
        content: '确定要清空所有播放历史吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              const userId = userManager.getUserId()
              await historyManager.clearHistory(userId)
              this.getHistory() // 重新获取列表
              uni.showToast({
                title: '已清空历史',
                icon: 'success'
              })
            } catch (error) {
              uni.showToast({
                title: '清空失败',
                icon: 'none'
              })
            }
          }
        }
      })
    },
    
    // 返回上一页
    goBack() {
      uni.navigateBack()
    },
    
    // 跳转到首页
    goToHome() {
      uni.switchTab({
        url: '/pages/home/home'
      })
    },
    
    // 格式化时间
    formatTime(timeString) {
      const date = new Date(timeString)
      const now = new Date()
      const diff = now - date
      const minutes = Math.floor(diff / (1000 * 60))
      const hours = Math.floor(diff / (1000 * 60 * 60))
      const days = Math.floor(diff / (1000 * 60 * 60 * 24))
      
      if (minutes < 1) {
        return '刚刚'
      } else if (minutes < 60) {
        return `${minutes}分钟前`
      } else if (hours < 24) {
        return `${hours}小时前`
      } else if (days === 1) {
        return '昨天'
      } else if (days < 7) {
        return `${days}天前`
      } else {
        return `${date.getMonth() + 1}月${date.getDate()}日`
      }
    }
  }
}
</script>

<style scoped>
.history-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f0f8f0 0%, #e8f5e8 100%);
}

.nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: calc(env(safe-area-inset-top, 40rpx) + 120rpx);
  background: rgba(255, 255, 255, 0.95);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 32rpx;
  z-index: 999;
  padding-top: calc(env(safe-area-inset-top, 40rpx) + 40rpx);
  border-bottom: 1px solid rgba(107, 142, 107, 0.1);
}

.nav-left, .nav-right {
  width: 80rpx;
}

.back-icon, .clear-icon {
  font-size: 36rpx;
  color: #4a6b4a;
  padding: 16rpx;
}

.nav-center {
  flex: 1;
  text-align: center;
}

.nav-title {
  font-size: 36rpx;
  font-weight: 500;
  color: #4a6b4a;
}

/* 页面标题区域 */
.page-header {
  position: fixed;
  top: calc(env(safe-area-inset-top, 40rpx) + 160rpx);
  left: 0;
  right: 0;
  padding: 40rpx 32rpx 32rpx;
  background: linear-gradient(135deg, #f0f8f0 0%, #e8f5e8 100%);
  z-index: 1;
}

.page-title {
  font-size: 48rpx;
  font-weight: 600;
  color: #4a6b4a;
  display: block;
  margin-bottom: 16rpx;
}

.page-subtitle {
  font-size: 28rpx;
  color: #6b8e6b;
  display: block;
}

.history-list {
  padding-top: calc(env(safe-area-inset-top, 40rpx) + 360rpx);
  padding-bottom: 120rpx;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 280rpx 32rpx;
  text-align: center;
}

.empty-icon {
  font-size: 120rpx;
  margin-bottom: 32rpx;
  opacity: 0.3;
}

.empty-text {
  font-size: 32rpx;
  color: #6b8e6b;
  margin-bottom: 16rpx;
}

.empty-desc {
  font-size: 28rpx;
  color: #999;
  margin-bottom: 48rpx;
}

.empty-btn {
  background: linear-gradient(135deg, #6b8e6b 0%, #4a6b4a 100%);
  color: white;
  border: none;
  border-radius: 44rpx;
  padding: 24rpx 48rpx;
  font-size: 28rpx;
}

.song-list {
  padding: 0 32rpx 40rpx;
}

.song-item {
  display: flex;
  align-items: center;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 16rpx;
  padding: 32rpx;
  margin-bottom: 32rpx;
  box-shadow: 0 8rpx 32rpx rgba(74, 107, 74, 0.15);
  transition: all 0.3s ease;
}

.song-info {
  flex: 1;
  display: flex;
  align-items: center;
  min-width: 0;
}

.song-cover {
  width: 120rpx;
  height: 120rpx;
  border-radius: 16rpx;
  margin-right: 32rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
}

.song-details {
  flex: 1;
  min-width: 0;
}

.song-name {
  font-size: 36rpx;
  font-weight: 600;
  color: #4a6b4a;
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-bottom: 12rpx;
}

.song-artist {
  font-size: 30rpx;
  color: #6b8e6b;
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-bottom: 12rpx;
}

.song-time {
  font-size: 26rpx;
  color: #999;
}

.song-actions {
  display: flex;
  align-items: center;
  gap: 24rpx;
}

.play-btn {
  font-size: 40rpx;
  color: #4a6b4a;
  padding: 20rpx;
  background: rgba(107, 142, 107, 0.1);
  border-radius: 50%;
  width: 80rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.remove-btn {
  font-size: 48rpx;
  color: #ff6b6b;
  padding: 20rpx;
  font-weight: bold;
  background: rgba(255, 107, 107, 0.1);
  border-radius: 50%;
  width: 80rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>